package com.jshoperxms.controller.api.langdu;

import com.jshoperxms.Response;
import com.jshoperxms.components.wechat.templatemsg.TemplateMsgController;
import com.jshoperxms.controller.api.langdu.vo.YdRecordCommentVo;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.maths.Arith;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.entity.*;
import com.jshoperxms.service.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 2018/10/17.
 * Des:
 */
@RestController
@RequestMapping("/api/record/comment")
public class YdRecordCommentTController extends BaseTController {


    @Resource
    private YdRecordCommentTService ydRecordCommentTService;

    @Resource
    private MemberTService memberTService;

    @Resource
    private YdRecordRdTService ydRecordRdTService;

    @Resource
    private TemplateMsgController templateMsgController;

    @Resource
    private YdRecordImpressRdTService ydRecordImpressRdTService;

    @Resource
    private SysWxpushRpTService sysWxpushRpTService;

    /**
     * 保存朗读评论
     * @param rq
     * @return
     */
    @RequestMapping(value="/saveRdComment",method= RequestMethod.POST)
    public ResponseEntity saveRdComment(@RequestBody YdRecordCommentVo rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getWxopenid())&&StringUtils.isNotBlank(rq.getRecordid())){
            Criterion criterion= Restrictions.eq("wxopenid",rq.getWxopenid());
            MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion);
            YdRecordRdT ydRecordRdT=this.ydRecordRdTService.findByPK(YdRecordRdT.class,rq.getRecordid());
            if(memberT!=null&&ydRecordRdT!=null){
                YdRecordCommentT bean=new YdRecordCommentT();
                bean.setId(PrimaryKey.get().toString());
                bean.setRecordid(ydRecordRdT.getId());
                bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                bean.setCreatetime(DateTools.getSystemTimeLong());
                bean.setCreatorid("0");
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(1);
                bean.setRctitle(StaticKey.EMPTY);
                bean.setRcname(rq.getRcname());
                bean.setCommentcontent(rq.getCommentcontent());
                bean.setScore(rq.getImpressscore());
                bean.setRctype("1");//1评论 2 回复评论
                bean.setCommentreplyid(StaticKey.EMPTY);
                bean.setRcmemberid(memberT.getId());
                bean.setIsvirtualadd("0");//1虚拟增加 0 真实增加
                bean.setStoreid(StaticKey.EMPTY);
                bean.setTargetmemberid(ydRecordRdT.getMemberid());//评论的目标用户ID暂时不记录
                bean.setIsreviewed("1");//1审核 0 未审核
                bean.setReviewedtime(DateTools.getSystemTimeLong());
                bean.setZan(0);
                bean.setCai(0);
                bean.setAvatarurl(rq.getAvatarurl());
                bean.setWxopenid(rq.getWxopenid());
                bean.setTargetwxopenid(ydRecordRdT.getWxopenid());
                this.ydRecordCommentTService.save(bean);
                this.updateRdCommentCount(ydRecordRdT);
                sendTemplateToNotice(rq);
                responsedata.put(TagWords.SUCCESS,true);
                //增加印象分数记录
                saveImpressSocre(bean,rq.getImpressscore(),ydRecordRdT);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);
    }

    /**
     * 保存印象评分记录
     * @param yc
     * @param impressscore
     */
    private void saveImpressSocre(YdRecordCommentT yc,int impressscore,YdRecordRdT ydRecordRdT){

        YdRecordImpressRdT bean=new YdRecordImpressRdT();
        bean.setId(PrimaryKey.get().toString());
        bean.setRecordid(yc.getRecordid());
        bean.setStatus(BaseEnums.DataUsingState.USING.getState());
        bean.setCreatetime(DateTools.getSystemTimeLong());
        bean.setCreatorid("0");
        bean.setUpdatetime(DateTools.getSystemTimeLong());
        bean.setVersiont(1);
        bean.setScore(impressscore);
        bean.setAvatarurl(yc.getAvatarurl());
        bean.setWxopenid(yc.getWxopenid());
        bean.setNick(yc.getRcname());
        bean.setIscalip(0);
        bean.setMemberid(yc.getRcmemberid());
        this.ydRecordImpressRdTService.save(bean);
        //计算阅读平均分
        if(impressscore!=0){
            this.calAvgRecordScore(yc.getRecordid(),ydRecordRdT);
        }

    }


    private void calAvgRecordScore(String recordid,YdRecordRdT ydRecordRdT){
        //查询并计算平均分
        Criterion criterion=Restrictions.eq("recordid",recordid);
        List<YdRecordImpressRdT>impressRdTS=this.ydRecordImpressRdTService.findByCriteria(YdRecordImpressRdT.class,criterion);
        int sumscore=0;
        for(YdRecordImpressRdT r:impressRdTS){
            sumscore+=r.getScore();
        }
        int avgscore= sumscore/impressRdTS.size();
        ydRecordRdT.setGscore(avgscore);
        ydRecordRdT.setUpdatetime(DateTools.getSystemTimeLong());
        ydRecordRdT.setVersiont(ydRecordRdT.getVersiont()+1);
        this.ydRecordRdTService.update(ydRecordRdT);
    }

    /**
     * 发送模版消息
     * @param bean
     */
    private void sendTemplateToNotice(YdRecordCommentVo bean){
        YdRecordRdT ydRecordRdT=this.ydRecordRdTService.findByPK(YdRecordRdT.class,bean.getRecordid());
        if(ydRecordRdT!=null) {
            Criterion criterion=Restrictions.eq("wxopenid",ydRecordRdT.getWxopenid());
            SysWxpushRpT sysWxpushRpT=this.sysWxpushRpTService.findOneByCriteria(SysWxpushRpT.class,criterion);
            if(sysWxpushRpT!=null){
                System.out.println("评价时间是"+DateTools.formateLongDateToString(bean.getCreatetime()/1000));
                templateMsgController.sendNoticToLangDuAuthorThanReceiveComment(sysWxpushRpT.getFormid(), bean.getCommentcontent(), bean.getRcname(), sysWxpushRpT.getWxopenid(), ydRecordRdT.getId());
            }
        }
    }


    /**
     * 更新评论总记录数量
     * @param rq
     */
    private void updateRdCommentCount(YdRecordRdT rq){
        if(rq!=null){
            System.out.println("更新评论的总数"+rq.getGcomment());
            rq.setGcomment(rq.getGcomment()+1);
            rq.setUpdatetime(DateTools.getSystemTimeLong());
            rq.setVersiont(rq.getVersiont()+1);
            this.ydRecordRdTService.update(rq);

        }
    }


//    @RequestMapping(value="/ts",method= RequestMethod.POST)
//    public ResponseEntity ts(){
//        Map<String,Object> responsedata=new HashMap<>();
//        List<YdRecordCommentT>commentTS=this.ydRecordCommentTService.findAll(YdRecordCommentT.class);
//        for(YdRecordCommentT commentT:commentTS){
//            YdRecordRdT bean=this.ydRecordRdTService.findByPK(YdRecordRdT.class,commentT.getRecordid());
//            if(bean!=null){
//                bean.setGcomment(bean.getGcomment()+1);
//                bean.setUpdatetime(DateTools.getSystemTimeLong());
//                bean.setVersiont(bean.getVersiont()+1);
//                this.ydRecordRdTService.update(bean);
//                responsedata.put(TagWords.SUCCESS,true);
//            }
//        }
//
//        return Response.success();
//    }

    /**
     * 获取阅读内容评论
     * @param rq
     * @return
     */
    @RequestMapping(value="/findRecordComments",method= RequestMethod.POST)
    public ResponseEntity findRecordComments(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getRecordid())){
            int currentPage=rq.getStart();
            int lineSize=rq.getLength();
            Criterion criterion=Restrictions.and(Restrictions.eq("recordid",rq.getRecordid())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
            int records=this.ydRecordCommentTService.count(YdRecordCommentT.class,criterion).intValue();
            List<YdRecordCommentT> list=this.ydRecordCommentTService.findByCriteriaByPage(YdRecordCommentT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
            rq.setRecordsTotal(records);
            responsedata.put("results",list);
            responsedata.put("start",rq.getNextPageNo());
            responsedata.put("totalPage",rq.getTotalPage());
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);

    }


}
